package com.bruce.download.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * http工具类
 * <br>CreateDate  2021/09/14 16:17:34
 *
 * @author luotuan
 * @version 1.0.0
 */
public class HttpUtils {
    /**
     * 获取下载文件大小
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static long getHttpFileContentLength(String url) throws IOException {
        int contentLength;
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = getHttpURLConnection(url);
            contentLength = httpURLConnection.getContentLength();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return contentLength;
    }

    /**
     * 获取链接
     *
     * @param url url
     * @return HttpURLConnection
     * <br>CreateDate 2021/09/14 17:12:35
     * @author luotuan
     * @since 1.0.0
     **/
    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL httpUrl = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        //发送标识信息
        httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1");
        return httpURLConnection;
    }

    /**
     * 分块下载
     *
     * @param url   url
     * @param start 开始
     * @param end   结束
     * @return HttpURLConnection
     * <br>CreateDate 2021/09/14 17:13:33
     * @author luotuan
     * @since 1.0.0
     **/
    public static HttpURLConnection getHttpURLConnection(String url, long start, long end) throws IOException {
        HttpURLConnection urlConnection = getHttpURLConnection(url);
        LogUtils.info("下载的区间时：{}-{}", start, end);
        if (end != 0) {
            urlConnection.setRequestProperty("RANGE", "bytes=" + start + "-" + end);
        } else {
            urlConnection.setRequestProperty("RANGE", "bytes=" + start + "-");
        }
        return urlConnection;
    }

    public static String getHttpFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}
